package com.atguigu.sparsearray;
/**
 * description:
 * Created by 才睡醒 on 2021-05-07
 */
public class SparseArray {
    public static  void main(String[] args){

        //创建一个原始的二维数组11*11

        //0表示没有棋子，1表示黑子，2表示蓝子
        int chessArr1[][] = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        //输出原始二维数组
        System.out.println("原始数组----------------");
        for (int [] row: chessArr1) {
            for(int data: row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        //将二维数组转换为稀疏数组
        //遍历二维数组，得到
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j]!=0){
                    sum++;
                }
            }

        }
        System.out.println("--------------------------");
        System.out.println("原始数组中的有效值有"+sum+"个");
        //创建对应的稀疏数组
        int sparseArray[][] = new int[sum+1][3];
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;
        int count = 0;
        //遍历原始数组，给稀疏数组赋值
        for(int i=1;i<11;i++){
            for(int j=1;j<11;j++){
                if(chessArr1[i][j]!=0) {
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = chessArr1[i][j];
                }
            }
        }
        //输出稀疏数组
        System.out.println("稀疏数组---------------------");
        for (int i = 0; i < sparseArray.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n",sparseArray[i][0],sparseArray[i][1],sparseArray[i][2]);
        }
        //恢复稀疏数组的原始数组
        int chessArr2[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            chessArr2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        //输入恢复后的稀疏数组
        System.out.println("恢复后的原始数组--------------------");
        for (int [] row: chessArr2) {
            for(int data: row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }

}
